package com.landiao.ctrler;

import java.text.MessageFormat;
import java.util.Date;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.landiao.common.Constant;
import com.landiao.common.factory.ResultMsgFactory;
import com.landiao.common.pojo.ResultMsg;
import com.landiao.common.utils.CodecUtils;
import com.landiao.common.utils.HttpClientUtil;
import com.landiao.entities.IdentifyCode;
import com.landiao.service.IdentifyCodeService;

/**
 *
 */
@Controller
@RequestMapping("/identifycode")
public class IdentifyCodeCtrler {
	
	protected static final Logger log = LoggerFactory.getLogger(IdentifyCodeCtrler.class);
	
	private static final String SMS_MESS = "【蓝调社区】您好，您的注册邀请码是：{0}，有效时间为10分钟，过期请重新获取邀请码。";
	@Autowired
	private IdentifyCodeService service;

	/**
	 * 生成验证码
	 */
	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg create(String phone,String action) {
		if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(action)){
			return ResultMsgFactory.failMsg();
		}
		String verifyCode = RandomStringUtils.randomNumeric(6);
		log.debug("验证码：{}",verifyCode);

		try{
			boolean result = HttpClientUtil.postSmsMessage(phone, MessageFormat.format(SMS_MESS, verifyCode));
			
			if(!result){//短信发送失败
				return ResultMsgFactory.fail("短信验证码发送失败");
			}
			IdentifyCode code = new IdentifyCode();
//			code.setCompId(compId);
			code.setCreTime(new Date());
			code.setCode(verifyCode);
			code.setIdentifyCodeId(CodecUtils.getUUID());
			code.setExtCol(action);
			code.setPhone(phone);
			code.setIsUsed(Constant.IDENTIFY_CODE_ISUSED_NO);
			this.service.save(code);
			ResultMsg resultMsg = ResultMsgFactory.successMsg();
			resultMsg.addParam("identifyCodeId", code.getIdentifyCodeId());
			return resultMsg;
		}catch(Exception e){
			e.printStackTrace();
			log.error("验证码发送失败：{}",e.getMessage());
			return ResultMsgFactory.fail("验证码发送失败");
		}
	}
}
